﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Data;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using System.Web;
using System.Configuration;
using System.Xml;
#region 数据库操作
using ADOX;  //32位                
using System.Data.OleDb;//32位
#endregion

using System.Management;
using Newtonsoft.Json.Linq;
using System.Drawing;
using System.Security.Cryptography;
using System.Web.Script.Serialization;
using System.Collections;
using System.Text.RegularExpressions;

namespace df
{

    /// <summary>
    /// 不要在winform的继承对象里写初始函数，否则会报错
    /// </summary>
    public class share : Form
    {

        /// <summary>
        /// 设置默认数据
        /// </summary>
        void defaultData()
        {


            string[] sql = new string[] {
                string.Format("insert into {0}([name],[value]) values('{1}','{2}')",config. tableConfig,config. switchDb, 0),
                string.Format("insert into {0}([name],[value]) values('{1}','{2}')",config. tableConfig,config. cur_Index, 0),
                string.Format("insert into {0}([name],[value]) values('{1}','{2}')",config. tableConfig,config. cur_Id, 1),
                string.Format("insert into {0}([name],[value]) values('{1}','{2}')", config.tableConfig, config.switchAutoSave, 1),
                string.Format("insert into {0}([name],[value]) values('{1}','{2}')",config. tableConfig,config. cloud_nm, "df"),
                string.Format("insert into {0}([name],[value]) values('{1}','{2}')",config. tableConfig, config.cloud_pw, ""),
                string.Format("insert into {0}([name],[value]) values('{1}','{2}')",config. tableConfig,config.token, ""),
                string.Format("insert into {0}([name],[value]) values('{1}','{2}')",config. tableConfig, config.mail_ac, "df_business@qq.com"),
            string.Format("insert into {0}([name],[value]) values('{1}','{2}')", config.tableConfig, config.mail_pw, "siblsbqueqlrdbeh"),
            string.Format("insert into {0}([name],[value]) values('{1}','{2}')",config. tableConfig, config.text_bgcolor, "#C7EDCC"),
            string.Format("insert into {0}([name],[value]) values('{1}','{2}')",config. tableConfig, config.text_font, "宋体, 10.5pt"),
            string.Format("insert into {0}([name],[value]) values('{1}','{2}')",config. tableConfig, config.form_location, "0|0"),
            string.Format("insert into {0}([name],[value]) values('{1}','{2}')",config. tableConfig, config.form_size, "600|500"),
            string.Format("insert into {0}([name],[value]) values('{1}','{2}')",config. tableConfig, config.auto_save_delay, "15"),
            string.Format("insert into `{0}`([title],[text],[date]) values('{1}','{2}','{3}')", config.tableNote,"使用说明",@"
------------------------------------------------------------------------
F3：最小化 
F4：更新； 
F5：显示/隐藏书签栏； 
F6：显示/隐藏搜索框； 
F7：显示/隐藏电子书柜（“键盘”按钮开启的情况下）； 
F11：插入当前时间； 
------------------------------------------------------------------------
鼠标右键：打开工具栏
------------------------------------------------------------------------
ctrl+a：全选； 
ctrl+s：保存； 
------------------------------------------------------------------------

------------------------------------------------------------------------

替身：由于下载数据会清空本地原有的所有数据，于是在清空前生成本地原有数据的备份，始终保留上一次的数据，每一次下载都会覆盖一次替身 

------------------------------------------------------------------------
© Df 2020", DateTime.Now)
            };
            foreach (string item in sql)
            {
                query(item, Type.exe, Type.mainDb);
            }

        }


        public void createNote()
        {

            //文档
            cols = new List<columns>();
            cols.Add(new columns() { name = "title", type = DataTypeEnum.adVarWChar, size = 30 });
            cols.Add(new columns() { name = "text", type = DataTypeEnum.adLongVarWChar, size = 100 });
            cols.Add(new columns() { name = "date", type = DataTypeEnum.adVarWChar, size = 30 });

            createTable(config.tableNote, cols);
        }


        List<columns> cols = new List<columns>();
        /// <summary>
        /// 初始化数据
        /// </summary>
        public void Cdb()
        {
            try
            {

                if (!File.Exists(Path.GetFullPath(config.mainMdb)))
                {
                    if (MessageBox.Show(config.mainMdb + "不存在，是否新建？", "注意", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                    {
                        createDatabase(config.mainMdb);
                        //文档
                        createNote();

                        ////公用参数
                        cols = new List<columns>();
                        cols.Add(new columns() { name = "name", type = DataTypeEnum.adVarWChar, size = 30 });
                        cols.Add(new columns() { name = "value", type = DataTypeEnum.adLongVarWChar, size = 100 });

                        createTable(config.tableConfig, cols);

                        defaultData();

                    }
                    else
                    {
                        Dispose();
                        //@base.Debug_Write("创建数据库出错");
                    }
                }

            }
            catch (Exception err)
            {
                @base.Debug_Write(err.ToString());
            }
        }
        /// <summary>
        /// 创建数据库
        /// </summary>
        /// <param name="dbName"></param>
        void createDatabase(string dbName)
        {
            Catalog catalog = new Catalog();
            catalog.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbName + ";Jet OLEDB:Engine Type=5");
        }

        /// <summary>
        /// 字段参数
        /// </summary>
        class columns
        {
            public string name;
            public DataTypeEnum type;
            public int size;
        }

        /// <summary>
        /// 创建表
        /// </summary>
        /// <param name="tablename">表名</param>
        /// <param name="col">字段组</param>
        void createTable(string tablename, List<columns> col)
        {

            Catalog catalog = new Catalog();
            ADODB.Connection cn = new ADODB.Connection();
            cn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + config.mainMdb, null, null, -1);//1、建立连接
            catalog.ActiveConnection = cn;
            Table table = new Table();
            table.Name = tablename;//table name
            Column column = new Column();
            column.ParentCatalog = catalog;
            column.Name = "Id";//1:id
            column.Type = DataTypeEnum.adInteger;
            column.DefinedSize = 9;
            column.Properties["AutoIncrement"].Value = true;
            table.Columns.Append(column, DataTypeEnum.adInteger, 0);
            table.Keys.Append("PrimaryKey", KeyTypeEnum.adKeyPrimary, column, null, null);

            foreach (columns item in col)
            {
                table.Columns.Append(item.name, item.type, item.size);
            }
            catalog.Tables.Append(table);
            cn.Close();//关闭连接 
        }




        /// <summary>
        /// 常量
        /// </summary>
        public enum Type
        {
            select, exe, insert, update_title, update_text, update_auto, mainDb, backupDb, red, black, start, end
        }
        /// <summary>
        /// note表模板
        /// </summary>
        public class notes
        {
            public string title, txt; public int id;
            public notes(string ti, string tx, int Id = 0)
            {
                id = Id;
                title = ti;
                txt = tx;
            }

        }
        /// <summary>
        /// 设置config
        /// </summary>
        /// <param name="name"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public int updateConfig(string name, object val, Type db = Type.mainDb)
        {

            val = val.ToString();
            string sql = string.Format("UPDATE `{0}` SET [value]='{1}' WHERE name ='{2}'", config.tableConfig, val, name);
            int rt = (int)query(sql, Type.exe, db);
            return rt;
        }

        /// <summary>
        /// 读取公用参数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string readConfig(string name)
        {
            string rt = "";
            string sql = string.Format("select value from `{0}` where name='{1}'", config.tableConfig, name);  //输入查询语句 
            DataTable dt = (DataTable)query(sql, Type.select);

            rt = dt.Rows[0][0].ToString();
            return rt;
        }

        /// <summary>
        /// 执行sql语句
        /// </summary>
        /// <param name="sql">sql</param>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public object query(string sql, Type type = Type.exe, Type db = Type.mainDb, notes sqlPara = null)
        {
            object rt = 0;
            try
            {
                //1、建立连接
                OleDbConnection cnn = new OleDbConnection();
                cnn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\" + (db == Type.mainDb ? config.mainMdb : config.backupMdb);
                //2、打开连接
                cnn.Open();

                OleDbCommand cmd = new OleDbCommand(sql, cnn);
                switch (type)
                {
                    case Type.select:
                        OleDbDataReader odrReader = cmd.ExecuteReader();  //建立读取
                        int size = odrReader.FieldCount; //数据列数
                        DataTable dt = new DataTable();//dt.Rows[行][列]
                        DataColumn dc;//行
                        DataRow dr;//列

                        //获取字段名（表格中每列的名字）
                        for (int i = 0; i < size; i++)
                        {
                            dc = new DataColumn(odrReader.GetName(i));
                            dt.Columns.Add(dc);
                        }
                        //获取数据（每行与列名对应的数据）
                        while (odrReader.Read())
                        {
                            dr = dt.NewRow();
                            for (int i = 0; i < size; i++)
                            {
                                dr[odrReader.GetName(i)] = odrReader[odrReader.GetName(i)].ToString();
                            }
                            dt.Rows.Add(dr);
                        }

                        odrReader.Close();     //关闭连接
                        cnn.Dispose();
                        rt = dt;
                        break;
                    case Type.exe:
                        //给sql添加参数，防止出现单引号之类的字符而报错
                        if (sqlPara != null)
                        {
                            if (!sqlPara.title.isEmptyOrNullOrUndefine())
                            {
                                OleDbParameter para_title = new OleDbParameter("@title", DbType.String);
                                para_title.Value = sqlPara.title;
                                cmd.Parameters.Add(para_title);
                            }
                            if (sqlPara.txt != null)
                            {
                                OleDbParameter para_txt = new OleDbParameter("@text", DbType.String);
                                para_txt.Value = sqlPara.txt;
                                cmd.Parameters.Add(para_txt);
                            }
                        }

                        rt = cmd.ExecuteNonQuery();
                        break;
                    default:
                        break;
                }

                cmd.Dispose();
                cnn.Dispose();

            }
            catch (Exception ex)
            {
                @base.Debug_Write(sql + "\n" + ex.ToString());

            }
            return rt;
        }

        public void err(Label err, string msg)
        {
            err.Text = msg;
        }



        /// <summary>
        /// 所有的post处理
        /// </summary>
        /// <param name="url"></param>
        /// <param name="para"></param>
        /// <returns></returns>
        public JObject post(string url, Dictionary<string, object> para)
        {
            string token = readConfig(config.token);
            para.Add("token", token);
            var rt = http.post(url, para);

            if (rt == null)
            {
                MessageBox.Show("数据返回错误");
            }

            return rt;
        }

        /// <summary>
        /// 修改winform属性
        /// 很重要
        /// </summary>
        private void InitializeComponent()
        {
            Control.CheckForIllegalCrossThreadCalls = false; //允许跨线程调用控件
            this.SuspendLayout();
            // 
            // share
            // 
            this.BackColor = System.Drawing.Color.AliceBlue;
            this.ClientSize = new System.Drawing.Size(0, 0);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Name = "share";
            this.ResumeLayout(false);

        }



    }





    #region 方法库
    public class @base
    {


        /// <summary>
        /// 检查文件是否被占用
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool IsFileInUse(string fileName)
        {

            bool inUse = false;
            FileStream fs = null;

            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
                fs.Close();

            }
            catch
            {
                inUse = true;
            }
            return inUse;//true表示正在使用,false没有使用

        }


        /// <summary>
        /// 结束进程
        /// </summary>
        public static void kill()
        {
            Process processes = Process.GetCurrentProcess();
            string name = processes.ProcessName;

            Process[] ps = Process.GetProcesses();
            foreach (Process item in ps)
            {
                if (item.ProcessName == name)
                {
                    item.Kill();
                }
            }
        }

        /// <summary>
        /// 执行cmd命令
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        bool cmd(string str)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.WriteLine(str);
            p.StandardInput.WriteLine("exit");
            p.Dispose();
            return true;
        }


        //写文件，自动换行
        static void FileW(string str, string fileN = "error.txt")
        {
            try
            {
                if (File.Exists(fileN))
                {
                    File.AppendAllText(fileN, str + "\r\n\r\n\r\n");
                }
                else
                {
                    File.Create(fileN).Dispose();
                    File.WriteAllText(fileN, str + "\r\n\r\n\r\n");
                }
            }
            catch
            {

            }

        }
        /// <summary>
        /// 输出错误信息
        /// </summary>
        /// <param name="msg"></param>
        public static void Debug_Write(string msg)
        {
            try
            {
                FileW(msg);
                System.Diagnostics.Debug.WriteLine(msg);
                //if (MessageBox.Show(msg) == DialogResult.OK)
                //{
                //    //Exit();
                //}
            }
            catch
            {
                Console.WriteLine(msg);
            }
        }
        /// <summary>
        /// 调用管理员权限运行一个指定路径的程序
        /// </summary>
        /// <param name="src"></param>
        public void AdminRun(string src)
        {
            Process.Start(new ProcessStartInfo
            {
                FileName = src,
                Verb = "runas"
            });
        }
        /// <summary>
        /// 当前进程休眠指定的秒数
        /// </summary>
        /// <param name="second"></param>
        public static void sleep(double second)
        {
            System.Threading.Thread.Sleep(Convert.ToInt32(second * 1000));
        }
















        #region 操作程序的配置文件   //xml格式
        //       <userSettings>  
        //  <Book.UI.Properties.Settings>  
        //    <setting name="userName" serializeAs="String">  
        //      <value></value>  
        //    </setting>  
        //  </Book.UI.Properties.Settings>  
        //</userSettings>



        public enum xmlSettings : uint
        {
            add_addAedit = 0,
            add_del = 1,
            add_read = 2
        }

        public enum appSet : int
        {
            read = 315,
            add = 1,
            edit = 2,
            del = 0
        }

        public bool XML_Exit(string 节点)
        {
            string congfigFile = Application.ExecutablePath + ".config";
            XmlDocument document = new XmlDocument();
            document.Load(congfigFile);
            XmlNode root = document.SelectSingleNode("configuration");
            if (root.SelectSingleNode(节点) == null)
                return false;
            else return true;

        }


        static void XML(string key, string value, xmlSettings set = xmlSettings.add_addAedit)
        {
            string filename = "";
            try
            {
                filename = System.Windows.Forms.Application.ExecutablePath + ".config";
            }
            catch
            {

            }
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(filename);
            XmlNode xmlNode = xmlDocument.SelectSingleNode("configuration");
            if (set == xmlSettings.add_addAedit)
            {
                XmlNode xmlNode2 = xmlNode.SelectSingleNode("appSettings");
                if (xmlNode2 == null)
                {
                    XmlElement xmlElement = xmlDocument.CreateElement("appSettings");
                    XmlElement xmlElement2 = xmlDocument.CreateElement("add");
                    xmlElement2.SetAttribute("key", key);
                    xmlElement2.SetAttribute("value", value);
                    xmlElement.AppendChild(xmlElement2);
                    xmlNode.AppendChild(xmlElement);
                }
                else
                {
                    XmlNode xmlNode3 = xmlNode2.SelectSingleNode("add");
                    if (xmlNode3 == null)
                    {
                        XmlElement xmlElement2 = xmlDocument.CreateElement("add");
                        xmlElement2.SetAttribute("key", key);
                        xmlElement2.SetAttribute("value", value);
                        xmlNode2.AppendChild(xmlElement2);
                        xmlNode.AppendChild(xmlNode2);
                    }
                    else
                    {
                        XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/configuration/appSettings/add");
                        bool flag = false;
                        foreach (XmlNode xmlNode4 in xmlNodeList)
                        {
                            try
                            {
                                if (xmlNode4.Attributes["key"].Value != null)
                                {
                                    if (xmlNode4.Attributes["key"].Value == key)
                                    {
                                        xmlNode4.Attributes["value"].Value = value;
                                        flag = true;
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                        if (!flag)
                        {
                            XmlElement xmlElement2 = xmlDocument.CreateElement("add");
                            xmlElement2.SetAttribute("key", key);
                            xmlElement2.SetAttribute("value", value);
                            xmlNode2.AppendChild(xmlElement2);
                            xmlNode.AppendChild(xmlNode2);
                        }
                    }
                }
            }
            xmlDocument.Save(filename);
        }

        static string XML(string key, xmlSettings set = xmlSettings.add_read)
        {
            string filename;
            filename = System.Windows.Forms.Application.ExecutablePath + ".config";
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(filename);
            XmlNode xmlNode = xmlDocument.SelectSingleNode("configuration");
            string result;
            switch (set)
            {
                case xmlSettings.add_del:
                    if (xmlNode.SelectSingleNode("appSettings") != null)
                    {
                        if (xmlNode.SelectSingleNode("appSettings").SelectSingleNode("add") != null)
                        {
                            XmlNode xmlNode2 = xmlNode.SelectSingleNode("appSettings");
                            XmlNodeList childNodes = xmlNode.SelectSingleNode("appSettings").ChildNodes;
                            for (int i = 0; i < childNodes.Count; i++)
                            {
                                XmlElement xmlElement = (XmlElement)childNodes.Item(i);
                                if (xmlElement.GetAttribute("key") == key)
                                {
                                    xmlNode2.RemoveChild(xmlElement);
                                }
                                if (i < childNodes.Count)
                                {
                                    i--;
                                }
                            }
                        }
                    }
                    xmlDocument.Save(filename);
                    break;
                case xmlSettings.add_read:
                    if (xmlNode.SelectSingleNode("appSettings") != null)
                    {
                        if (xmlNode.SelectSingleNode("appSettings").SelectSingleNode("add") != null)
                        {
                            XmlNode xmlNode2 = xmlNode.SelectSingleNode("appSettings");
                            XmlNodeList childNodes = xmlNode.SelectSingleNode("appSettings").ChildNodes;
                            foreach (XmlNode xmlNode3 in childNodes)
                            {
                                try
                                {
                                    if (xmlNode3.Attributes["key"].Value != null)
                                    {
                                        if (xmlNode3.Attributes["key"].Value == key)
                                        {
                                            result = xmlNode3.Attributes["value"].Value;
                                            return result;
                                        }
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                    break;
            }
            result = "";
            return result;
        }

        static void AppSetting(string key, string value)
        {
            XML(key, value);
        }
        static string AppSetting(string key, appSet appsets = appSet.read)
        {
            switch (appsets)
            {

                case appSet.read:
                    //根据Key读取<add>元素的Value                  
                    //return System.Configuration.ConfigurationManager.AppSettings[key] == null ? XML(key) : System.Configuration.ConfigurationManager.AppSettings[key];
                    return XML(key);
                case appSet.del:
                    //Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    ////删除<add>元素
                    //config.AppSettings.Settings.Remove(key);
                    XML(key, xmlSettings.add_del);
                    break;
                default:

                    break;
            }
            return "";
        }



        public static string AppSettingCaR(string key, string value)
        {
            string result;
            try
            {
                if (AppSetting(key, appSet.read).isEmptyOrNullOrUndefine())
                {
                    AppSetting(key, value);
                }
                result = AppSetting(key, appSet.read);
            }
            catch
            {
                result = value;
            }
            return result;
        }


        #endregion




        #region 文件处理



        public void 打包文件夹(string fileFrom, string fileTo)
        {
            Zip z = new Zip();
            //只允许打包文件夹
            z.ZipFile(fileFrom, fileTo);//会覆盖已经存在的rar文件
        }






        string GetLocationOfFuncLine(StackFrame sf)
        {
            Console.WriteLine(" Stack trace for current level: {0}", sf.ToString());//完整信息         
            Console.WriteLine(" File: {0}", sf.GetFileName());//文件
            Console.WriteLine(" Method: {0}", sf.GetMethod().Name);//方法
            Console.WriteLine(" Line Number: {0}", sf.GetFileLineNumber());//行数
            Console.WriteLine(" Column Number: {0}", sf.GetFileColumnNumber());//列数
            return string.Format("【{0}】-->【{1}】-->【{2}】", sf.GetFileName(), sf.GetMethod(), sf.GetFileLineNumber());
        }




        //读取文件中全部内容
        public string FileR(string src = "1.txt")
        {
            string result;
            try
            {
                StreamReader streamReader = new StreamReader(src, Encoding.Default);
                src = streamReader.ReadToEnd();
                streamReader.Close();
                result = src;
            }
            catch
            {
                result = "error";
            }
            return result;
        }


        //读取一个文件的某一行，存在则读出，不存在则创建
        public string FileCaR(int 行数 = 1, string val = "", string src = "1.txt")
        {
            if (!File.Exists(src))
            {
                string[] str = new string[行数];
                for (int i = 0; i < str.Length; i++)
                {
                    str[i] = val;
                }
                FileW(str, src);
            }
            else if (FileR_Line_N(src) < 行数)
            {
                for (int i = 0; i < 行数 - FileR_Line_N(src); i++)
                {
                    File.AppendAllText(src, val + "\r\n");
                }
            }
            return FileR(行数, src);

        }


        //以覆盖的形式往文件中写入多行
        public void FileW(string[] 多行数据, string src = "1.txt")
        {
            File.Create(src).Dispose();
            string x = "";
            foreach (var item in 多行数据)
            {
                x += item + "\r\n";
            }
            File.WriteAllText(src, x);
        }

        //往某一行写入数据
        public bool FileW(int 行数 = 1, string value = "", string src = "1.txt")
        {
            try
            {
                string[] t = File.ReadAllLines(src);
                t[行数 - 1] = value;
                string xxx = "";
                foreach (var item in t)
                {
                    xxx += item + "\r\n";
                }
                File.Create(src).Dispose();
                File.WriteAllText(src, xxx);
                return true;
            }
            catch
            {
                return false;
            }
        }


        //读取某一行的数据
        public string FileR(int 行数 = 1, string src = "1.txt")
        {
            try
            {
                string[] t = File.ReadAllLines(src);
                return t[行数 - 1];
            }
            catch
            {
                return "";
            }
        }

        //获取文件中的行数
        public int FileR_Line_N(string src = "1.txt")
        {
            string[] t = File.ReadAllLines(src);
            return t.Length;
        }

        //删除一个文件
        public string FileDel(string fileN = "1.txt")
        {
            string result = "";
            try
            {
                if (File.Exists(fileN))
                {
                    File.Delete(fileN);
                }
                result = "Del done!";
            }
            catch (Exception ex)
            {
                result = "Error============>" + ex.Message;
            }
            return result;
        }

        //批量复制文件 //会覆盖已存在的文件  //fileCopy(new string[,] { { "1.txt", "11.txt" }, { "2.txt", "22.txt" } });
        public void fileCopy(string[,] str)
        {
            for (int i = 0; i < str.GetLength(0); i++)
            {
                System.IO.File.Copy(str[i, 0], str[i, 1], true);
            }
        }


        //获取文件的上次访问时间
        public DateTime getFileTime(string src)
        {

            FileInfo f1 = new FileInfo(src);//http://www.cnblogs.com/yisheng/archive/2013/01/05/2845239.html
                                            //  TimeSpan ts = DateTime.Now - f1.LastWriteTime;
            return f1.LastWriteTime;
        }


        //获取文件的名称和后缀
        public string getFileName(string src)
        {
            return System.IO.Path.GetFileName(src);
        }

        //遍历一个目录下的文件和文件夹，获取完整路径，赋值给list，然后返回该list
        public List<string> FindFileAndDire(string sSourcePath)
        {
            List<String> list = new List<string>();
            //遍历文件夹
            DirectoryInfo theFolder = new DirectoryInfo(sSourcePath);
            foreach (var item in theFolder.GetDirectories())
            {
                list.Add(item.FullName);
            }
            foreach (var item in theFolder.GetFiles())
            {
                list.Add(item.FullName);
            }
            return list;
        }

        //清空一个路径下的所有文件和文件夹
        public static bool ClearFileAndDire(string sSourcePath)
        {
            try
            {
                Directory.Delete(sSourcePath, true);
                return true;
            }
            catch
            {
                return false;
            }
        }




        //遍历一个目录下的所有文件，获取名字，赋值给list，然后返回该list
        public List<string> FindFile(string sSourcePath)
        {
            List<String> list = new List<string>();
            //遍历文件夹
            DirectoryInfo theFolder = new DirectoryInfo(sSourcePath);
            foreach (var item in theFolder.GetFiles())
            {
                list.Add(item.Name);
            }
            return list;
        }


        //遍历一个目录下的所有文件夹，获取名字，赋值给list，然后返回该list
        public List<string> FindDir(string sSourcePath)
        {
            List<String> list = new List<string>();
            //遍历文件夹
            DirectoryInfo theFolder = new DirectoryInfo(sSourcePath);
            foreach (var item in theFolder.GetDirectories())
            {
                list.Add(item.Name);
            }

            return list;
        }

        //遍历一个目录下的所有文件，获得完整路径,输入“c:”会输出“C:\Windows\system32\”下的文件,正确的写法是“c:\”
        public List<string> FindFilePath(string sSourcePath)
        {
            List<String> list = new List<string>();
            //遍历文件
            string[] files = System.IO.Directory.GetFiles(sSourcePath);
            foreach (string path in files)
            {
                list.Add(path);
            }
            return list;
        }


        //文件转二进制
        public byte[] 文件转二进制(string 文件路径)
        {
            //根据图片文件的路径使用文件流打开，并保存为byte[]
            FileStream fs = new FileStream(文件路径, FileMode.Open);//可以是其他重载方法
            byte[] byData = new byte[fs.Length];
            fs.Read(byData, 0, byData.Length);
            fs.Close();
            return byData;
        }


        class ApiCopyFile
        {//http://blog.sina.com.cn/s/blog_4171e80d0100mg4g.html

            private const int FO_COPY = 0x0002;
            private const int FOF_ALLOWUNDO = 0x0040;//如果设置，这个标志强迫函数移动被删除的文件到‘回收站’中。否则，文件将被物理地从磁盘上删除。

            private const int FOF_SILENT = 0x0004;//这个操作不回馈给用户，就是说，不显示进度对话框。相关的消息框仍然显示。
            private const int FOF_NOCONFIRMATION = 0x0010;  //这个标志使函数对任何遇到的消息框都自动回答Yes。
                                                            //  
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 0)]
            public struct SHFILEOPSTRUCT
            {
                public IntPtr hwnd;
                [MarshalAs(UnmanagedType.U4)]
                public int wFunc;
                public string pFrom;
                public string pTo;
                public short fFlags;
                [MarshalAs(UnmanagedType.Bool)]
                public bool fAnyOperationsAborted;
                public IntPtr hNameMappings;
                public string lpszProgressTitle;
            }
            [DllImport("shell32.dll", CharSet = CharSet.Auto)]
            static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
            public static bool DoCopy(string strSource, string strTarget)
            {
                SHFILEOPSTRUCT fileop = new SHFILEOPSTRUCT();
                fileop.wFunc = FO_COPY;
                fileop.pFrom = strSource;
                fileop.lpszProgressTitle = "复制大文件";
                fileop.pTo = strTarget;
                fileop.fFlags = FO_COPY | FOF_NOCONFIRMATION;
                return SHFileOperation(ref fileop) == 0;
            }
        }

        //多线程
        static void MainThreadWithParameters(object o)
        {
            Str d = (Str)o;  //类型转换
            Console.WriteLine("Running in a thread---多线程在执行");

            CopyFiles显示进度(d.str1, d.str2);
        }

        public struct Str
        {
            public string str1;
            public string str2;
        }





        //批量设置文件行，调用系统功能进行复制
        // new string[,]{{ @"E:\D\项目\Console&Form",@"G:\"}}
        public bool CopyFiles(string[,] str)
        {
            try
            {
                int xx = 1;
                for (int i = 0; i < str.GetLength(0); i++)
                {
                    // 调用
                    var data = new Str { str1 = FileCaR(xx, str[i, 0], "df"), str2 = FileCaR(xx + 1, str[i, 1], "df") };
                    Thread t2 = new Thread(MainThreadWithParameters);
                    t2.Start(data);  // 传入参数
                    xx += 2;
                }
                return true;
            }
            catch
            {

                return false;
            }
        }

        //CopyFiles显示进度(@"D:\DF\",@"E:\");    //将指定目录以覆盖的方式原样复制到另一个目录
        public static bool CopyFiles显示进度(string 来源路径, string 目标路径)
        {
            try
            {
                ApiCopyFile.DoCopy(来源路径, 目标路径);
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion




      



    }

    public enum 度量单位
    {
        百 = 100,
        千 = 1000,
        万 = 10000,
        十万 = 100000,
        百万 = 1000000,
        千万 = 10000000,
        亿 = 100000000
    }

    #endregion


    #region//通用的拓展方法

    public static class df_whatever//必须是静态类才可以添加扩展方法
    {

        /// <summary>
        /// 字符串转Unicode
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <returns>Unicode编码后的字符串</returns>
        public static string String2Unicode(this string source)
        {
            var bytes = Encoding.Unicode.GetBytes(source);
            var stringBuilder = new StringBuilder();
            for (var i = 0; i < bytes.Length; i += 2)
            {
                stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
            }
            return stringBuilder.ToString();
        }

        /// <summary>
        /// Unicode转字符串
        /// </summary>
        /// <param name="source">经过Unicode编码的字符串</param>
        /// <returns>正常字符串</returns>
        public static string Unicode2String(this string source)
        {
            return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(source, x => Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)).ToString());
        }

        /// <summary>
        /// Json 字符串 转换为 DataTable数据集合
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static DataTable ToDataTable(this object json)
        {
            DataTable dataTable = new DataTable();  //实例化
            DataTable result;
            try
            {
                JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
                ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json.ToString());
                if (arrayList.Count > 0)
                {
                    foreach (Dictionary<string, object> dictionary in arrayList)
                    {
                        if (dictionary.Keys.Count<string>() == 0)
                        {
                            result = dataTable;
                            return result;
                        }
                        if (dataTable.Columns.Count == 0)
                        {
                            foreach (string current in dictionary.Keys)
                            {
                                dataTable.Columns.Add(current, dictionary[current].GetType());
                            }
                        }
                        DataRow dataRow = dataTable.NewRow();
                        foreach (string current in dictionary.Keys)
                        {
                            dataRow[current] = dictionary[current];
                        }

                        dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
                    }
                }
            }
            catch
            {
            }
            result = dataTable;
            return result;
        }


        public static string ToJson(this DataTable table)
        {
            var JsonString = new StringBuilder();
            if (table.Rows.Count > 0)
            {
                JsonString.Append("[");
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    JsonString.Append("{");
                    for (int j = 0; j < table.Columns.Count; j++)
                    {
                        if (j < table.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == table.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\"");
                        }
                    }
                    if (i == table.Rows.Count - 1)
                    {
                        JsonString.Append("}");
                    }
                    else
                    {
                        JsonString.Append("},");
                    }
                }
                JsonString.Append("]");
            }
            return JsonString.ToString();
        }


        /// <summary>
        /// MD5字符串加密
        /// </summary>
        /// <param name="txt"></param>
        /// <returns>加密后字符串</returns>
        public static string md5(this string txt)
        {
            using (MD5 mi = MD5.Create())
            {
                byte[] buffer = Encoding.Default.GetBytes(txt);
                //开始加密
                byte[] newBuffer = mi.ComputeHash(buffer);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < newBuffer.Length; i++)
                {
                    sb.Append(newBuffer[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }


        //声明扩展方法
        //扩展方法必须是静态的，Add有三个参数       
        //this 必须有，string表示我要扩展的类型，stringName表示对象名
        //三个参数this和扩展的类型必不可少，对象名可以自己随意取如果需要传递参数，再增加一个变量即可
        //http://www.cnblogs.com/potential/archive/2012/11/04/2754148.html

        /// <summary>
        /// 获取一个字符串中某个字符串的出现次数
        /// </summary>
        /// <param name="str"></param>
        /// <param name="cs"></param>
        /// <returns></returns>
        public static int findStrNum(this string str, string cs)
        {

            string r = str.Replace(cs, "");
            int num = (str.Length - r.Length) / cs.Length;
            return num;
        }
        /// <summary>
        /// 在字符串中根据提供的条件截取出指定的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="cs">条件数组</param>
        /// <param name="Num">有相同字符的情况选择第几个</param>
        /// <returns></returns>
        public static string findStr(this string str, string[] cs, int Num = 1)
        {

            switch (cs.Length)
            {
                case 1://获取某个字符串到末尾
                    if (str.IndexOf(cs[0]) < 0)
                        return "no.1:" + "        " + cs[0] + "        " + str.IndexOf(cs[0]);
                    for (int i = 0; i < Num; i++)//有多个相同的字符串的情况下，设置获取第几个字符串，默认获取第一个
                    {
                        str = str.Substring(str.IndexOf(cs[0]) + cs[0].Length, str.Length - (str.IndexOf(cs[0]) + cs[0].Length));
                    }
                    break;
                case 2://在上面的基础上，获取开头到下一个字符串
                    if (str.IndexOf(cs[0]) < 0)
                        return "no.1:" + "        " + cs[0] + "        " + str.IndexOf(cs[0]);
                    for (int i = 0; i < Num; i++)
                    {
                        str = str.Substring(str.IndexOf(cs[0]) + cs[0].Length, str.Length - (str.IndexOf(cs[0]) + cs[0].Length));
                    }
                    if (str.IndexOf(cs[1]) < 1)
                        return "no.2:" + "        " + cs[1] + "        " + str.IndexOf(cs[1]);
                    str = str.Substring(0, str.IndexOf(cs[1])); break;
                case 3://在上面的基础上，获取开头到下一个字符串
                    if (str.IndexOf(cs[0]) < 0)
                        return "no.1:" + "        " + cs[0] + "        " + str.IndexOf(cs[0]);
                    for (int i = 0; i < Num; i++)
                    {
                        str = str.Substring(str.IndexOf(cs[0]) + cs[0].Length, str.Length - (str.IndexOf(cs[0]) + cs[0].Length));
                    }
                    if (str.IndexOf(cs[1]) < 0)
                        return "no.2:" + "        " + cs[1] + "        " + str.IndexOf(cs[1]);
                    str = str.Substring(str.IndexOf(cs[1]) + cs[1].Length, str.Length - (str.IndexOf(cs[1]) + cs[1].Length));
                    if (str.IndexOf(cs[2]) < 1)
                        return "no.3:" + "        " + cs[2] + "        " + str.IndexOf(cs[2]);
                    str = str.Substring(0, str.IndexOf(cs[2])); break;
                default:
                    break;
            }
            return str;
        }


        public static string df_字符串倒序(this string text)
        {
            char[] charArray = text.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }
        public static DateTime df_拼接时间(this string text)
        {
            try
            {
                return Convert.ToDateTime(text);
            }
            catch
            {
                return DateTime.Now;
            }
        }

        //时间格式化
        public static string 时间_yyyy年M月d日hh时mm分ss秒(this DateTime text)
        {
            string result;
            try
            {
                result = text.ToString("yyyy年M月d日HH时mm分ss秒");
            }
            catch
            {
                result = "";
            }
            return result;
        }

        public static string 时间_yyyyMMddhhmmss(this DateTime text)
        {
            string result;
            try
            {
                result = text.ToString("yyyyMMddHHmmss");
            }
            catch
            {
                result = "";
            }
            return result;
        }
        public static string 时间_yyyyMMdd(this DateTime text)
        {
            string result;
            try
            {
                result = text.ToString("yyyyMMdd");
            }
            catch
            {
                result = "";
            }
            return result;
        }

        public static string 时间_yyyy年M月d日(this DateTime text)
        {
            string result;
            try
            {
                result = text.ToString("yyyy年M月d日");
            }
            catch
            {
                result = "";
            }
            return result;
        }

        public static string 时间_yyyy_M_d(this DateTime text)
        {
            string result;
            try
            {
                result = text.ToString("yyyy-M-d");
            }
            catch
            {
                result = "";
            }
            return result;
        }


        public static string 小数To百分比(this string text)
        {

            double Fx = text.ToDouble() * 100;
            return Fx.ToString();

        }

        //时间添加一周
        public static DateTime AddWeek(this DateTime text, int Num = 1)
        {
            DateTime result;
            try
            {
                result = text.AddDays((double)(Num * 7));
            }
            catch
            {
                result = DateTime.Now;
            }
            return result;
        }

        public static int ToInt32(this string text)
        {
            try
            {
                return Convert.ToInt32(text);
            }
            catch
            {
                return 0;
            }
        }
        public static int ToInt32(this object text)
        {
            try
            {
                return Convert.ToInt32(text);
            }
            catch
            {
                return 0;
            }
        }
        public static bool ToBool(this int text)
        {
            try
            {
                return Convert.ToBoolean(text);
            }
            catch
            {
                return false;
            }
        }

        public static bool ToBool(this object text)
        {
            bool result;
            try
            {
                result = Convert.ToBoolean(text);
            }
            catch
            {
                result = false;
            }
            return result;
        }

        public static bool isEmptyOrNullOrUndefine(this string text)
        {
            bool result;
            try
            {
                if (text == "" || text == null || text == "undefined")
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
            }
            catch
            {
                result = false;
            }
            return result;
        }



        public static double 四舍五入(this double text)
        {
            double result;
            try
            {
                result = Math.Round(text, 2, MidpointRounding.AwayFromZero);
            }
            catch
            {
                result = 0.0;
            }
            return result;
        }

        public static decimal ToDecimal(this string text)
        {
            decimal result;
            try
            {
                result = Convert.ToDecimal(text);
            }
            catch
            {
                result = 00;
            }
            return result;
        }

        public static double ToDouble(this string text)
        {
            double result;
            try
            {
                result = Convert.ToDouble(text);
            }
            catch
            {
                result = 0.0;
            }
            return result;
        }

        //转化为个十百千万的double
        public static double ToDouble(this string text, 度量单位 x)
        {
            double result;
            try
            {
                result = Convert.ToDouble(text) / (double)x.ToInt32();
            }
            catch
            {
                result = 0.0;
            }
            return result;
        }
        public static string ToDoubleStr(this string text, int 小数点位数 = 1)
        {
            string result;
            try
            {
                string text2 = "";
                for (int i = 0; i < 小数点位数; i++)
                {
                    text2 += "0";
                }
                result = Convert.ToDouble(text).ToString("0." + text2);
            }
            catch
            {
                result = "";
            }
            return result;
        }


        //list转数组
        public static string[] ListToArr(this List<string> text)
        {
            try
            {

                return text.ToArray();

            }
            catch
            {
                return null;
            }

        }


        //数组转list
        public static List<string> ListToArr(this string[] text)
        {
            try
            {

                return new List<System.String>(text);

            }
            catch
            {
                return null;
            }

        }


        //list转数组
        //var xxx = ty.FindFilePath(b).筛选文件后缀(new string[]{"cs","js"});
        public static List<string> 筛选文件后缀(this List<string> text, string[] 后缀)
        {
            try
            {
                List<string> file = new List<string>();

                foreach (var item in text)
                {
                    foreach (var i in 后缀)
                    {
                        if (item.Split('.')[item.Split('.').Length - 1] == i)
                        {
                            file.Add(item);
                        }
                    }
                }
                return file;
            }
            catch
            {
                return null;
            }
        }

        public static void 保存图片(this System.Drawing.Image image, string 图片路径)
        {
            image.Save(图片路径);
            //  image.Save(System.Web.HttpContext.Current.Server.MapPath("./uploadfile/222.png"));
        }


        public static void 保存图标(this System.Drawing.Icon image, string 图片路径)
        {
            FileStream x = new FileStream(图片路径, FileMode.OpenOrCreate);
            image.Save(x);
        }


        //无损转换Image为Icon
        /// <summary>
        /// 转换Image为Icon
        /// </summary>
        /// <param name="image">要转换为图标的Image对象</param>
        /// <param name="nullTonull">当image为null时是否返回null。false则抛空引用异常</param>
        /// <exception cref="ArgumentNullException" />
        public static System.Drawing.Icon 图片转图标(this System.Drawing.Image image, bool nullTonull = false)
        {
            if (image == null)
            {
                if (nullTonull) { return null; }
                throw new ArgumentNullException("image");
            }

            using (MemoryStream msImg = new MemoryStream()
                              , msIco = new MemoryStream())
            {
                image.Save(msImg, System.Drawing.Imaging.ImageFormat.Png);

                using (var bin = new BinaryWriter(msIco))
                {
                    //写图标头部
                    bin.Write((short)0);           //0-1保留
                    bin.Write((short)1);           //2-3文件类型。1=图标, 2=光标
                    bin.Write((short)1);           //4-5图像数量（图标可以包含多个图像）

                    bin.Write((byte)image.Width);  //6图标宽度
                    bin.Write((byte)image.Height); //7图标高度
                    bin.Write((byte)0);            //8颜色数（若像素位深>=8，填0。这是显然的，达到8bpp的颜色数最少是256，byte不够表示）
                    bin.Write((byte)0);            //9保留。必须为0
                    bin.Write((short)0);           //10-11调色板
                    bin.Write((short)32);          //12-13位深
                    bin.Write((int)msImg.Length);  //14-17位图数据大小
                    bin.Write(22);                 //18-21位图数据起始字节

                    //写图像数据
                    bin.Write(msImg.ToArray());

                    bin.Flush();
                    bin.Seek(0, SeekOrigin.Begin);
                    return new System.Drawing.Icon(msIco);
                }
            }
        }
        public static System.Drawing.Image 图标转图片(this System.Drawing.Icon ico)
        {
            return System.Drawing.Image.FromHbitmap(ico.ToBitmap().GetHbitmap());
        }

        #region 进制处理

        // 二进制转图片
        public static System.Drawing.Image 二进制转图片(this byte[] streamByte)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            return img;
        }

        //图片转二进制
        public static byte[] 图片转二进制(this System.Drawing.Image imgPhoto)
        {
            //将Image转换成流数据，并保存为byte[]
            MemoryStream mstream = new MemoryStream();
            imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] byData = new Byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(byData, 0, byData.Length);
            mstream.Close();
            return byData;
        }

        //图标转二进制
        public static byte[] 图标转二进制(this System.Drawing.Icon ico)
        {
            //将Image转换成流数据，并保存为byte[]
            MemoryStream mstream = new MemoryStream();
            ico.Save(mstream);
            byte[] byData = new Byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(byData, 0, byData.Length);
            mstream.Close();
            return byData;
        }
        public static System.Drawing.Icon 二进制转图标(this byte[] streamByte)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            return img.图片转图标();
        }



        public static string 二进制转字符串(this byte[] s)
        {
            return Encoding.Unicode.GetString(s, 0, s.Length);
        }

        public static byte[] 字符串转二进制(this string s)
        {
            byte[] data = Encoding.Unicode.GetBytes(s);
            return data;
        }


        //jz必须是 2、8、10 或 16。
        /*
         * int a = 0xa; //a可以是十六进制格式         
         */
        public static string 十进制转其他进制字符串(this int a, int jz = 2)
        {

            string str;
            str = Convert.ToString(a, jz);
            return str;
        }

        //只支持单个数字的转换
        public static int 其他进制字符串转十进制(this string ejz, int jz = 2)
        {
            return Convert.ToInt32(ejz, jz);

        }

        public static string 二进制转十六进制字符串(this byte InByte)
        {
            return String.Format("{0:X2} ", InByte);
            //return String.Format("{0:X} ", InByte);
        }

        public static byte 其他进制字符串转二进制(this string s, int jz = 16)
        {
            return Convert.ToByte(s, jz);
        }


        public static string 二进制转十进制(this byte[] bytes)
        {
            return BitConverter.ToInt64(bytes, 0).ToString();

        }

        public static byte[] 十进制转二进制(this string bytes)
        {
            return Convert.FromBase64String(bytes);
        }
        public static string 以十进制打印二进制(this byte[] InBytes)
        {
            string StringOut = "";
            foreach (byte InByte in InBytes)
            {
                StringOut = StringOut + String.Format("{0} ", InByte);//取消最少二位的限制，输出格式不规范，但是可以减少空间占用
            }
            return StringOut;
        }


        // 把字节型转换成十六进制字符串  
        public static string 以十六进制打印二进制(this byte[] InBytes)
        {
            string StringOut = "";
            foreach (byte InByte in InBytes)
            {

                StringOut = StringOut + String.Format("{0:X} ", InByte);//取消最少二位的限制，输出格式不规范，但是可以减少空间占用
                                                                        //StringOut = StringOut + String.Format("{0:X2} ", InByte);//输出十六进制，最少二位，不足部分用0填充
            }
            return StringOut;
        }


        // 把十六进制字符串转换成字节型  
        public static byte[] 将打印的十六进制恢复成二进制(this string InString)
        {
            string[] ByteStrings;
            ByteStrings = InString.Split(" ".ToCharArray());
            byte[] ByteOut;
            ByteOut = new byte[ByteStrings.Length - 1];
            for (int i = 0; i < ByteOut.Length; i++)
            {
                ByteOut[i] = ByteStrings[i].其他进制字符串转二进制();
            }
            return ByteOut;
        }

        //将二进制数据以字符串形式打印出来
        public static string 打印二进制(this byte[] data)
        {

            StringBuilder result = new StringBuilder(data.Length * 8);

            foreach (byte b in data)
            {
                result.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
            }
            return result.ToString();

        }

        //将以字符串形式打印出来的二进制数据恢复为二进制
        public static byte[] 将打印的二进制恢复成二进制(this string s)
        {
            System.Text.RegularExpressions.CaptureCollection cs =
                    System.Text.RegularExpressions.Regex.Match(s, @"([01]{8})+").Groups[1].Captures;
            byte[] data = new byte[cs.Count];
            for (int i = 0; i < cs.Count; i++)
            {
                data[i] = Convert.ToByte(cs[i].Value, 2);
            }
            return data;

        }



        //字符串转十六进制字符串
        public static string Df_Encoding(this string s, Encoding encode = null)
        {
            return "Df-" + s.df_字符串倒序().字符串转十六进制字符串().df_字符串倒序();
        }


        //十六进制字符串转字符串
        public static string Df_UnCoding(this string s, Encoding encode = null)
        {
            return s.Substring(3, s.Length - 3).df_字符串倒序().十六进制字符串转字符串().df_字符串倒序();
        }


        /// 从汉字转换到16进制          
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <param name="fenge">是否每字符用逗号分隔</param>

        public static string 字符串转十六进制字符串(this string s, string charset = "utf-8", bool fenge = false)
        {
            if ((s.Length % 2) != 0)
            {
                //   s += " ";//空格
                //throw new ArgumentException("s is not valid chinese string!");
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            byte[] bytes = chs.GetBytes(s);
            string str = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                str += string.Format("{0:X}", bytes[i]);
                if (fenge && (i != bytes.Length - 1))
                {
                    str += string.Format("{0}", ",");
                }
            }
            return str.ToLower();
        }


        ///<summary>
        /// 从16进制转换成汉字     
        /// <param name="charset">编码,如"utf-8","gb2312"</param> 
        public static string 十六进制字符串转字符串(this string hex, string charset = "utf-8")
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("\n", "");
            hex = hex.Replace("\\", "");
            hex = hex.Replace(" ", "");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
            }
            // 需要将 hex 转换成 byte 数组。 
            byte[] bytes = new byte[hex.Length / 2];

            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。 
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                    System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message. 
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            return chs.GetString(bytes);
        }



        public static long DataTimeToLong(this DateTime dt)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            TimeSpan toNow = dt.Subtract(dtStart);
            long timeStamp = toNow.Ticks;
            timeStamp = long.Parse(timeStamp.ToString().Substring(0, timeStamp.ToString().Length - 4));
            return timeStamp;
        }

        public static DateTime LongToDateTime(this long d)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(d + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }

        //设置textBox的ctrl为全选
        public static void textBox里按ctrl则全选(this TextBox textBox1, KeyEventArgs textBox1_KeyDown_KeyEventArgs_e)
        {
            if (textBox1_KeyDown_KeyEventArgs_e.KeyCode == System.Windows.Forms.Keys.ControlKey)
                textBox1.Select(0, textBox1.TextLength);
        }


        public static DataTable 读取数据库(this OleDbConnection cnn, string sql语句 = "select * from FirstTable")
        {
            DataTable dt = new DataTable();//dt.Rows[行][列]
            DataColumn dc;//行
            DataRow dr;//列
            try
            {
                OleDbCommand odCommand = cnn.CreateCommand();   //建立SQL查询  
                odCommand.CommandText = sql语句;  //输入查询语句 
                OleDbDataReader odrReader = odCommand.ExecuteReader();  //建立读取  
                int size = odrReader.FieldCount; //查询并显示数据  
                for (int i = 0; i < size; i++)
                {
                    dc = new DataColumn(odrReader.GetName(i));
                    dt.Columns.Add(dc);
                }
                while (odrReader.Read())
                {
                    dr = dt.NewRow();
                    for (int i = 0; i < size; i++)
                    {
                        dr[odrReader.GetName(i)] = odrReader[odrReader.GetName(i)].ToString();
                    }
                    dt.Rows.Add(dr);
                }
                odrReader.Close();     //关闭连接
                cnn.Dispose();
            }
            catch
            {
            }
            return dt;
        }

    }

    #endregion

    #endregion





    /// <summary>
    /// 网络协议
    /// </summary>
    public class http
    {
        /// <summary>
        /// str转化为json
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        static JObject strTojson(string str)
        {
            try
            {

                Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(str);
                return obj;
            }
            catch
            {
                return null;
            }
        }


        /// <summary>
        /// 获取get数据
        /// </summary>
        /// <param name="strURL">   string strURL = "http://localhost/WinformSubmit.php?tel=11111&name=张三";</param>
        /// <returns></returns>
        public static JObject get(string strURL)
        {
            System.Net.HttpWebRequest request;
            // 创建一个HTTP请求
            request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            //request.Method="get";
            System.Net.HttpWebResponse response;
            response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string responseText = myreader.ReadToEnd();
            myreader.Close();
            return strTojson(responseText);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strURL">string strURL = "http://localhost/WinformSubmit.php";</param>
        /// <param name="para"></param>
        /// <returns></returns>
        public static JObject post(string strURL, Dictionary<string, object> para)
        {
            try
            {
                string result = "";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strURL);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                //req.ContentType = "text/plain";
                #region 添加Post 参数
                StringBuilder builder = new StringBuilder();
                int i = 0;
                foreach (var item in para)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value.ToString());
                    i++;
                }
                byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                #endregion
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                JObject rt = strTojson(result);
                return rt;

            }
            catch
            {
                return null;
            }
        }






        /// <summary>
        /// Http方式下载文件
        /// </summary>
        /// <param name="url">http地址</param>
        /// <param name="localfile">本地文件</param>
        /// <returns></returns>
        public bool Download(string url, string localfile)
        {
            bool flag = false;
            long startPosition = 0; // 上次下载的文件起始位置
            FileStream writeStream; // 写入本地文件流对象

            long remoteFileLength = GetHttpLength(url);// 取得远程文件长度
            System.Console.WriteLine("remoteFileLength=" + remoteFileLength);
            if (remoteFileLength == 745)
            {
                Console.WriteLine("远程文件不存在.");
                return false;
            }


            if (File.Exists(localfile))
            {

                Console.WriteLine("本地文件已存在.");
                //删除
                File.Delete(localfile);
            }

            writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件
            startPosition = 0;



            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接

                if (startPosition > 0)
                {
                    myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
                }


                Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流


                byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
                int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次

                long currPostion = startPosition;

                while (contentSize > 0)// 如果读取长度大于零则继续读
                {
                    currPostion += contentSize;
                    int percent = (int)(currPostion * 100 / remoteFileLength);
                    System.Console.WriteLine("percent=" + percent + "%");

                    writeStream.Write(btArray, 0, contentSize);// 写入本地文件
                    contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
                }

                //关闭流
                writeStream.Close();
                readStream.Close();

                flag = true;        //返回true下载成功
            }
            catch (Exception)
            {
                writeStream.Close();
                flag = false;       //返回false下载失败
            }

            return flag;
        }

        // 从文件头得到远程文件的长度
        private static long GetHttpLength(string url)
        {
            long length = 0;

            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
                HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();

                if (rsp.StatusCode == HttpStatusCode.OK)
                {
                    length = rsp.ContentLength;// 从文件头得到远程文件的长度
                }

                rsp.Close();
                return length;
            }
            catch
            {
                return length;
            }

        }


    }
}
